<template>
  <div class="submission-history">
    <el-table
      v-loading="loading"
      :data="submissions"
      stripe
      border
      :cell-style="{ padding: '12px 0' }"
      :header-cell-style="{ background: 'var(--el-fill-color-light)' }"
      style="width: 100%"
    >
      <el-table-column
        prop="id"
        label="#"
        width="80"
        align="center"
      />
      
      <el-table-column
        label="状态"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-tag
            :type="scope.row.status_class"
            effect="light"
            size="small"
          >
            {{ scope.row.status_display }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="problem_title"
        label="题目"
        min-width="200"
      />

      <el-table-column
        label="提交用户"
        min-width="150"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.username }}({{ scope.row.nick_name }})
        </template>
      </el-table-column>

      <el-table-column
        prop="language_display"
        label="语言"
        width="100"
        align="center"
      />

      <el-table-column
        prop="time_display"
        label="耗时"
        width="100"
        align="center"
      />

      <el-table-column
        prop="memory_display"
        label="内存"
        width="100"
        align="center"
      />

      <el-table-column
        prop="submit_time"
        label="提交时间"
        width="150"
        align="center"
      />

      <el-table-column
        label="操作"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="showSubmissionDetail(scope.row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 提交详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="提交详情"
      width="80%"
      destroy-on-close
    >
      <template v-if="currentSubmission">
        <div class="submission-detail">
          <!-- 基本信息 -->
          <div class="detail-header">
            <div class="detail-item">
              <span class="label">状态：</span>
              <el-tag :type="currentSubmission.status_class" effect="light">
                {{ currentSubmission.status_display }}
              </el-tag>
            </div>
            <div class="detail-item">
              <span class="label">提交用户：</span>
              {{ currentSubmission.username }}({{ currentSubmission.nick_name }})
            </div>
            <div class="detail-item">
              <span class="label">语言：</span>
              {{ currentSubmission.language_display }}
            </div>
            <div class="detail-item">
              <span class="label">耗时：</span>
              {{ currentSubmission.time_display }}
            </div>
            <div class="detail-item">
              <span class="label">内存：</span>
              {{ currentSubmission.memory_display }}
            </div>
            <div class="detail-item" v-if="currentSubmission.test_cases_passed !== null">
              <span class="label">测试用例：</span>
              {{ currentSubmission.test_cases_passed }}/{{ currentSubmission.total_test_cases }}
            </div>
          </div>

          <!-- 编译错误信息 -->
          <div v-if="currentSubmission.compile_output" class="compile-error">
            <h4>编译错误信息：</h4>
            <pre>{{ currentSubmission.compile_output }}</pre>
          </div>

          <!-- 代码 -->
          <div class="code-section">
            <h4>提交的代码：</h4>
            <div ref="codeRef" class="code-content"></div>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import CodeMirror from 'codemirror'
import codeApi from '@/api/code'
import type { SubmissionResult } from '@/api/code'

// 导入 CodeMirror 主题和模式
import 'codemirror/theme/dracula.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/clike/clike'
import 'codemirror/mode/python/python'

const props = defineProps<{
  problem: number
}>()

const route = useRoute()
const loading = ref(false)
const submissions = ref<SubmissionResult[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框相关
const dialogVisible = ref(false)
const currentSubmission = ref<SubmissionResult | null>(null)
const codeRef = ref<HTMLElement | null>(null)
let codeEditor: CodeMirror.Editor | null = null

// 获取提交记录
const fetchSubmissions = async () => {
  loading.value = true
  try {
    const response = await codeApi.getSubmissionList({
      problem: props.problem,
      page: currentPage.value,
      page_size: pageSize.value
    })
    
    if (response.code === 200) {
      submissions.value = response.data
      console.log('Submissions:', submissions.value)
      total.value = response.count || 0
    } else {
      throw new Error(response.msg || '获取提交记录失败')
    }
  } catch (error: any) {
    console.error('Fetch submissions error:', error)
    ElMessage.error(error.message || '获取提交记录失败')
    submissions.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 显示提交详情
const showSubmissionDetail = (submission: SubmissionResult) => {
  currentSubmission.value = submission
  dialogVisible.value = true

  // 在下一个 tick 初始化代码编辑器
  nextTick(() => {
    if (codeRef.value && currentSubmission.value) {
      if (codeEditor) {
        codeEditor
        codeEditor = null
      }

      codeEditor = CodeMirror(codeRef.value, {
        value: currentSubmission.value.code,
        mode: getModeByLanguage(currentSubmission.value.language_display),
        theme: 'dracula',
        lineNumbers: true,
        readOnly: true,
        viewportMargin: Infinity
      })
    }
  })
}

// 获取语言对应的编辑器模式
const getModeByLanguage = (lang: string) => {
  switch (lang) {
    case 'C':
    case 'C++':
      return 'text/x-c++src'
    case 'Python':
      return 'text/x-python'
    default:
      return 'text/x-c++src'
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchSubmissions()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchSubmissions()
}

// 监听路由参数变化
watch(
  () => props.problem,
  () => {
    currentPage.value = 1
    fetchSubmissions()
  },
  { immediate: true }
)

onMounted(() => {
  fetchSubmissions()
})
</script>

<style scoped>
.submission-history {
  padding: 20px;
}

/* 修复表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__body) {
  border-spacing: 0;
}

:deep(.el-table__row) {
  td {
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
  
  &:last-child td {
    border-bottom: none;
  }
}

:deep(.el-table__header) {
  th {
    background-color: var(--el-fill-color-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.problem-link {
  color: var(--el-color-primary);
  text-decoration: none;
}

.problem-link:hover {
  text-decoration: underline;
}

.submission-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
  padding: 16px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-item .label {
  color: var(--el-text-color-secondary);
}

.compile-error {
  margin-bottom: 24px;
}

.compile-error h4 {
  margin: 0 0 12px;
  color: var(--el-color-danger);
}

.compile-error pre {
  padding: 16px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
  color: var(--el-color-danger);
  white-space: pre-wrap;
  word-wrap: break-word;
}

.code-section h4 {
  margin: 0 0 12px;
}

.code-content {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  overflow: hidden;
}

:deep(.CodeMirror) {
  height: auto;
  font-family: 'Fira Code', monospace;
}

:deep(.el-dialog__body) {
  padding: 0;
}
</style>
